package com.chinasolf.controller;

import com.chinasolf.result.R;
import com.chinasolf.service.MsmService;
import com.chinasolf.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/msm")
public class MsmController {

    @Autowired
    private MsmService msmService;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    //发送短信接口
    @GetMapping("send/{phone}")
    public R sendCode(@PathVariable String phone){
        //验证码在有效时间内，不能再次发送的
        //根据手机号查询redis
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)){
            return R.ok();
        }
        //生成验证码
        code = RandomUtil.getFourBitRandom();
        //调用鼎信方法验证码发送
        boolean isSuccess = msmService.sendDx(phone,code);
        //发送成功，把发送的验证码存储到redis里面设置
        if(isSuccess){
            redisTemplate.opsForValue().set(phone,code,2, TimeUnit.MINUTES);
            return R.ok();
        }
        return R.error().message("验证码发送失败");
    }
}
